package com.yiper.controller;

import com.google.code.kaptcha.Constants;
import com.yiper.entity.Permission;
import com.yiper.entity.User;
import com.yiper.security.PasswordHelper;
import com.yiper.service.PermissionService;
import com.yiper.service.UserService;
import com.yiper.util.ResultUtil;
import com.yiper.util.UUIDUtil;
import com.yiper.vo.ResponseVo;
import com.yiper.vo.SystemConst;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * @version V1.0
 * @date 2018年8月8日
 * @author yiper
 */
@Controller
public class SystemController {
    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private LocaleResolver localeResolver;

    /*跳转首页*/
    @RequestMapping(value={"/","/index"})
    public String index(HttpServletRequest request){
        return "system/index";
    }

    /*跳转注册页*/
    @RequestMapping(value = "/register",method = RequestMethod.GET)
    public String register(){
        return "system/register";
    }

    @RequestMapping(value = "/register1",method = RequestMethod.GET)
    public String register1(){
        return "system/register";
    }

    /*提交注册*/
    @ResponseBody
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public ResponseVo register(HttpServletRequest request, User registerUser , String verification){
        //判断验证码
        String rightCode = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (StringUtils.isNotBlank(verification) && StringUtils.isNotBlank(rightCode) && verification.equals(rightCode)) {
            //验证码通过
        } else {
            return ResultUtil.error("验证码错误！");
        }
        String username = registerUser.getUsername();
        User user = userService.selectByUsername(username);
        if (null != user) {
            return ResultUtil.error("用户名已存在！");
        }
        registerUser.setUserId(UUIDUtil.getUniqueIdByUUId());
        registerUser.setStatus(SystemConst.DATA_VALID);
        Date date = new Date();
        registerUser.setCreateTime(date);
        PasswordHelper.encryptPassword(registerUser);
        //注册
        int registerResult = userService.register(registerUser);
        if(registerResult > 0){
            return ResultUtil.success("注册成功！");
        }else {
            return ResultUtil.error("注册失败，请稍后再试！");
        }
    }

    /*跳转登录页*/
    @RequestMapping(value = "/login" ,method = RequestMethod.GET)
    public String login1(HttpServletRequest request) {
        return "system/login";
    }

    /*提交注册*/
    @ResponseBody
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ResponseVo login(HttpServletRequest request, User user, String verification,
                            @RequestParam(value = "rememberMe", defaultValue = "0") Integer rememberMe) {
        //判断验证码
        String rightCode = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (StringUtils.isNotBlank(verification) && StringUtils.isNotBlank(rightCode) && verification.equals(rightCode)) {
            //验证码通过
        } else {
            return ResultUtil.error("验证码错误！");
        }
        String userName = user.getUsername();
        String passWord = user.getPassword();
        UsernamePasswordToken token = new UsernamePasswordToken(userName,passWord);
        try{
            token.setRememberMe(1 == rememberMe);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
        }catch (ExcessiveAttemptsException e){
            token.clear();
            return ResultUtil.error("该帐号密码输错五次 请明天再试！");
        }catch (AuthenticationException e) {
            token.clear();
            return ResultUtil.error("用户名或者密码错误！");
        }
        return ResultUtil.success("登录成功！");

    }


    /**
     * <p class="detail">
     * 功能:根据用户id查询当前用户拥有的菜单权限
     * </p>
     *
     * @return list
     * @author yiper
     * @date 2018.07.22 12:59:11
     */
    @PostMapping("/menu")
    @ResponseBody
    public List<Permission> getMenus(){
        String userId = ((User)SecurityUtils.getSubject().getPrincipal()).getUserId();
        List<Permission> permissionListList = permissionService.selectMenuByUserId(userId);
        return permissionListList;
    }


    /**
     * <p class="detail">
     * 功能:后台首页
     * </p>
     *
     * @return string
     * @author yiper
     * @date 2018.07.22 15:30:01
     */
    @GetMapping(value = {"/overview","/overview/{lang}"})
    public String overview(HttpServletRequest request, HttpServletResponse response,
                           @PathVariable(value = "lang",required = false) String lang ){
        if(SystemConst.LANG_EN.equals(lang) && StringUtils.isNotBlank(lang)){
            localeResolver.setLocale(request, response, Locale.ENGLISH);
        }else if(SystemConst.LANG_ZH.equals(lang) && StringUtils.isNotBlank(lang)){
            localeResolver.setLocale(request, response, Locale.CHINESE);
        } else {
            localeResolver.setLocale(request, response, LocaleContextHolder.getLocale());
        }
        return "system/overview";
    }



    /**
     * <p class="detail">
     * 功能:用户管理
     * </p>
     *
     * @return string
     * @author yiper
     * @date 2018.07.22 15:31:05
     */
    @GetMapping("/users")
    public String userPage(){
        return "user/list";
    }
    /**
     * <p class="detail">
     * 功能:角色管理
     * </p>
     *
     * @return string
     * @author yiper
     * @date 2018.07.24 13:29:35
     */
    @GetMapping("/roles")
    public String rolePage(){
        return "role/list";
    }

    /**
     * <p class="detail">
     * 功能:资源管理
     * </p>
     *
     * @return string
     * @author yiper
     * @date 2018.07.24 13:29:35
     */
    @GetMapping("/permissions")
    public String permissionPage(){
        return "permission/list";
    }

    /**
     * <p class="detail">
     * 功能:图标工具
     * </p>
     *
     * @return string
     * @author BaoWeiwei
     * @date 2018.07.22 18:02:51
     */
    @GetMapping(value = "/icons")
    public String getIcons(){
        return "tool/icons";
    }
}
